<script setup lang="ts">
import { nextTick, reactive, ref, toRaw } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { useViewScroll } from "@/hooks/scroll";
import { fx_shop_search_api } from "@/package/guider/api/tour_user";
import { Storage } from "@/utils/database";
import { Router } from "@/utils/router";
import { Toast } from "@/utils/toast";

import PageSticky from "@/components/page/sticky.vue";
import SearchTypeItem from "./components/search-type-item.vue";
import ListEmpty from "@/components/list/empty.vue";
import SearchProductItem from "./components/search-product-item.vue";
import SearchExpandBtn from "./components/search-expand-btn.vue";

const historyKey = "guider-store-search-history";

onLoad((options) => {
  historyList.value = Storage.getSync(historyKey) || [];
  tempData.id = options?.id || "";
});

const { scrollIndex, scrollToIndex } = useViewScroll();

const queryData = reactive({ keyword: "" });

const searchStatus = ref<"init" | "finish">("init"); // search：搜索中（聚焦）, finish：搜索完成
const searchClick = (type: "search" | "clear") => {
  if (type === "search") {
    const keyword = queryData.keyword.trim();
    if (!keyword) return;
    Toast.showLoading();
    fx_shop_search_api({ guider_id: tempData.id, keyword })
      .then((resp) => {
        const _typeList: any[] = [];
        // 线上课程
        const course = resp.course;
        if (course && course.length !== 0) {
          _typeList.unshift({ id: 5, name: "线上课程" });
        }
        // 商品
        const passport_shop = resp.passport_shop;
        if (passport_shop && passport_shop.length !== 0) {
          _typeList.unshift({ id: 4, name: "实物商品" });
        }
        // 手机导览
        const passport_guide = resp.passport_guide;
        if (passport_guide && passport_guide.length !== 0) {
          _typeList.unshift({ id: 3, name: "手机导览" });
        }
        // 线下精讲
        const tour = resp.tour;
        if (tour && tour.length !== 0) {
          _typeList.unshift({ id: 2, name: "人工讲解" });
        }
        // 全部
        if (_typeList.length !== 0) {
          _typeList.unshift({ id: 0, name: "全部" });
        }
        typeIndex.value = 0;
        typeList.value = _typeList;
        productList2.value = tour;
        goodsList.value = passport_guide;
        goodsList2.value = passport_shop;
        courseList.value = course;
        searchStatus.value = "finish";
        Toast.hideLoading();

        nextTick(() => {
          const _historyList = historyList.value;
          const index = _historyList.indexOf(keyword);
          if (index !== -1) _historyList.splice(index, 1);
          _historyList.unshift(keyword);
          historyList.value = _historyList.splice(0, 10);
          Storage.setSync(historyKey, toRaw(historyList.value));
        });
      })
      .catch(() => Toast.hideLoading());
  } else {
    queryData.keyword = "";
    searchStatus.value = "init";
  }
};

const historyList = ref<string[]>([]);
const historyClick = (key: string) => {
  if (key === "del") {
    historyList.value = [];
    Storage.deleteSync(historyKey);
  } else {
    queryData.keyword = key;
    searchClick("search");
  }
};

const typeIndex = ref(0);
const typeList = ref<any[]>([]);
const typeClick = (index: number) => {
  typeIndex.value = index;
  scrollToIndex(index);
};

const productList = ref<any[]>([]);
const productMore = ref(false);
const productClick = (id: string) => {
  Router.navigateTo(
    `/package/mall/pages/jps/detail?id=${id}&guiderId=${tempData.id}`
  );
};

const productList2 = ref<any[]>([]);
const productMore2 = ref(false);

const goodsList = ref<any[]>([]);
const goodsMore = ref(false);
const goodsClick = (id: string) => {
  Router.navigateTo(
    `/package/mall/pages/goods/detail?id=${id}&guiderId=${tempData.id}`
  );
};

const goodsList2 = ref<any[]>([]);
const goodsMore2 = ref(false);

const courseList = ref<any[]>([]);
const courseMore = ref(false);
const courseClick = (id: string) => {
  Router.navigateTo(
    `/package/study/pages/course/detail?id=${id}&guiderId=${tempData.id}`
  );
};

const tempData = { id: "" };
</script>

<template>
  <PageSticky background="#f9f9f9">
    <view class="search-bar">
      <view class="search-bar-wrapper">
        <icon type="search" size="28rpx" color="#999999" />
        <input
          class="search-bar-input"
          v-model="queryData.keyword"
          confirm-type="search"
          focus
          placeholder="输入搜索关键词"
          @confirm="searchClick('search')"
        />
        <icon
          v-show="queryData.keyword.length !== 0"
          type="clear"
          size="32rpx"
          color="#999999"
          @click="searchClick('clear')"
        />
      </view>
      <view class="search-bar-btn" @confirm="searchClick('search')">搜索</view>
    </view>

    <scroll-view
      class="search-type"
      v-if="searchStatus === 'finish' && typeList.length > 0"
      scroll-x
      enhanced
      :show-scrollbar="false"
    >
      <view class="search-type-space"></view>
      <view
        class="search-type-item"
        v-for="i of typeList"
        :key="i.id"
        @click="typeClick(i.id)"
      >
        <SearchTypeItem :isActive="typeIndex === i.id" :text="i.name" />
      </view>
    </scroll-view>
  </PageSticky>

  <view class="search-init" v-if="searchStatus === 'init'">
    <template v-if="historyList.length !== 0">
      <view class="search-init-title">搜索历史</view>
      <image
        class="search-init-del"
        src="/static/search-del.png"
        @click="historyClick('del')"
      />
      <view class="search-init-wrapper">
        <view
          class="search-init-keyword"
          v-for="i of historyList"
          :key="i"
          @click="historyClick(i)"
        >
          {{ i }}
        </view>
      </view>
    </template>
  </view>

  <scroll-view
    class="search-data"
    v-else
    scroll-y
    :scroll-into-view="`data-${scrollIndex}`"
  >
    <ListEmpty
      v-if="typeList.length === 0"
      text="没有找到合适结果，试试搜搜其他的吧~"
    />

    <template v-else>
      <view class="search-data-space" id="data-0"></view>

      <template v-if="productList2.length !== 0">
        <view class="search-data-title" id="data-2">
          金牌说（人工线下精讲预约）
        </view>
        <view class="search-data-wrapper">
          <view v-for="(i, d) of productList2" :key="i.id">
            <view
              class="search-data-item"
              v-if="d > 2 ? productMore2 : true"
              @click="productClick(i.id)"
            >
              <SearchProductItem :info="i" />
            </view>
          </view>
        </view>
        <view class="search-data-expand" v-if="productList2.length > 3">
          <SearchExpandBtn v-model="productMore2" />
        </view>
      </template>

      <template v-if="goodsList.length !== 0">
        <view class="search-data-title" id="data-3">手机导览</view>
        <view class="search-data-wrapper">
          <view v-for="(i, d) of goodsList" :key="i.id">
            <view
              class="search-data-item"
              v-if="d > 2 ? goodsMore : true"
              @click="goodsClick(i.id)"
            >
              <SearchProductItem :info="i" />
            </view>
          </view>
        </view>
        <view class="search-data-expand" v-if="goodsList.length > 3">
          <SearchExpandBtn v-model="goodsMore" />
        </view>
      </template>

      <template v-if="goodsList2.length !== 0">
        <view class="search-data-title" id="data-4">实物商品</view>
        <view class="search-data-wrapper">
          <view v-for="(i, d) of goodsList2" :key="i.id">
            <view
              class="search-data-item"
              v-if="d > 2 ? goodsMore2 : true"
              @click="goodsClick(i.id)"
            >
              <SearchProductItem :info="i" />
            </view>
          </view>
        </view>
        <view class="search-data-expand" v-if="goodsList2.length > 3">
          <SearchExpandBtn v-model="goodsMore2" />
        </view>
      </template>

      <template v-if="courseList.length > 0">
        <view class="search-data-title" id="data-5">线上课程</view>
        <view class="search-data-wrapper">
          <view
            class="search-data-item"
            v-for="i of courseList"
            :key="i.id"
            @click="courseClick(i.id)"
          >
            <SearchProductItem :info="i" />
          </view>
        </view>
        <view class="search-data-expand" v-if="courseList.length > 3">
          <SearchExpandBtn v-model="courseMore" />
        </view>
      </template>

      <view class="search-data-safe"></view>
    </template>
  </scroll-view>
</template>

<style lang="scss">
page {
  padding-bottom: 0;
}

.search-bar {
  display: flex;
  align-items: center;
  height: 100rpx;
  padding-left: 30rpx;
  padding-right: 10rpx;

  .search-bar-wrapper {
    display: flex;
    align-items: center;
    flex-grow: 1;
    min-width: 0;
    height: 70rpx;
    padding: 0 30rpx;
    border-radius: 36rpx;
    background-color: #ffffff;
  }

  .search-bar-input,
  .search-bar-btn {
    font-size: 28rpx;
    color: #333333;
    line-height: 40rpx;
  }

  .search-bar-input {
    flex-grow: 1;
    min-width: 0;
    margin-left: 10rpx;
    margin-right: 20rpx;
  }

  .search-bar-btn {
    padding: 0 20rpx;
    margin-left: 10rpx;
    line-height: 56rpx;
    font-weight: bold;
    white-space: nowrap;
  }
}

.search-type {
  height: 80rpx;
  white-space: nowrap;

  .search-type-space,
  .search-type-item {
    display: inline-block;
    vertical-align: top;
  }

  .search-type-space {
    width: 30rpx;
  }

  .search-type-item {
    padding: 0 10rpx;
    margin-top: 10rpx;
    margin-right: 40rpx;
  }
}

.search-init {
  position: relative;
  padding-top: 28rpx;

  .search-init-title {
    padding-left: 30rpx;
    margin-bottom: 20rpx;
    font-size: 30rpx;
    color: #2d2d2d;
    line-height: 40rpx;
    font-weight: bold;
  }

  .search-init-del {
    position: absolute;
    top: 34rpx;
    right: 30rpx;
    width: 24rpx;
    height: 28rpx;
  }

  .search-init-wrapper {
    display: flex;
    align-items: flex-start;
    flex-wrap: wrap;
    padding-left: 30rpx;
    padding-bottom: 24rpx;
  }

  .search-init-keyword {
    padding: 0 26rpx;
    margin-right: 24rpx;
    margin-bottom: 24rpx;
    font-size: 28rpx;
    color: #999999;
    line-height: 60rpx;
    border-radius: 36rpx;
    background-color: #f6f6f6;
  }
}

.search-data {
  height: calc(100vh - 180rpx);

  .search-data-space {
    height: 40rpx;
  }

  .search-data-title {
    padding-left: 30rpx;
    margin-bottom: 30rpx;
    font-size: 30rpx;
    color: #333333;
    line-height: 42rpx;
    font-weight: bold;
  }

  .search-data-item {
    position: relative;
    margin: 20rpx 30rpx;
  }

  .search-data-expand {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 10rpx;
  }

  .search-data-safe {
    height: 50rpx;
    padding-bottom: env(safe-area-inset-bottom);
  }
}
</style>